<template>
  <div>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               title="添加学员"
               :visible="open"
               width="700px"
               append-to-body
               @close="cancel()"
    >
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="学员" prop="studentIds">
          <el-cascader
            style="width: 500px;"
            :show-all-levels="false"
            :options="students"
            :props="{
              emitPath: false,
              multiple: true,
              label: 'name',
              value: 'id',
              children: 'children',
            }"
            v-model="form.studentIds"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addstudentlist,
  putCourseStudentList
} from '@/api/course/course'
import allSelect from '@/components/allSelect'

export default {
  components: { allSelect },
  props: {
    open: Boolean,
    courseId: Number
  },
  data() {
    return {
      // 表单参数
      form: {
        studentIds: []
      },
      // 表单校验
      rules: {
        studentIds: { required: true, message: '请选择学生', trigger: 'blur' }
      },
      students: [],
      resourseList: []
    }
  },
  watch: {
    open(e) {
      if (e) {
        this.reset()
        this.getAddstudentlist()
      }
    }
  },
  mounted() {
  },
  methods: {
    async getAddstudentlist() {
      let res = await addstudentlist(this.courseId)
      this.resourseList = res.data
      let list = res.data.reduce((acc, cur) => {
        const branchIndex = acc.findIndex(
          (item) => item.branch_id === cur.branch_id
        )
        if (branchIndex === -1) {
          acc.push({
            branch_id: cur.branch_id,
            branch_name: cur.branch_name,
            majors: [
              {
                major_id: cur.major_id,
                major_name: cur.major_name,
                classes: [
                  {
                    class_id: cur.class_id,
                    class_name: cur.class_name,
                    students: [{ student_id: cur.student_id, name: cur.name }]
                  }
                ]
              }
            ]
          })
        } else {
          const majorIndex = acc[branchIndex].majors.findIndex(
            (item) => item.major_id === cur.major_id
          )
          if (majorIndex === -1) {
            acc[branchIndex].majors.push({
              major_id: cur.major_id,
              major_name: cur.major_name,
              classes: [
                {
                  class_id: cur.class_id,
                  class_name: cur.class_name,
                  students: [{ student_id: cur.student_id, name: cur.name }]
                }
              ]
            })
          } else {
            const classIndex = acc[branchIndex].majors[
              majorIndex
              ].classes.findIndex((item) => item.class_id === cur.class_id)
            if (classIndex === -1) {
              acc[branchIndex].majors[majorIndex].classes.push({
                class_id: cur.class_id,
                class_name: cur.class_name,
                students: [{ student_id: cur.student_id, name: cur.name }]
              })
            } else {
              acc[branchIndex].majors[majorIndex].classes[
                classIndex
                ].students.push({ student_id: cur.student_id, name: cur.name })
            }
          }
        }
        return acc
      }, [])
      list.map((item) => {
        item.id = item.branch_id
        item.name = item.branch_name
        item.children = item.majors
        delete item.majors
        item.children.map((item2) => {
          item2.id = item2.major_id
          item2.name = item2.major_name
          item2.children = item2.classes
          delete item.classes
          item2.children.map((item3) => {
            item3.id = item3.class_id
            item3.name = item3.class_name
            item3.children = item3.students
            delete item2.students
            item3.children.map((item4) => {
              item4.id = item4.student_id
            })
          })
        })
      })
      this.students = list
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (valid) {
            let data = JSON.parse(JSON.stringify(this.form.studentIds))
            for (let i = 0; i < data.length; i++) {
              for (let j = 0; j < this.resourseList.length; j++) {
                if (data[i] == this.resourseList[j].student_id) {
                  data[i] = {
                    studentId: this.resourseList[j].student_id,
                    classId: this.resourseList[j].class_id
                  }
                }
              }
            }
            putCourseStudentList({
              courseId: this.courseId,
              students: data
            }).then(() => {
              this.$modal.msgSuccess('添加学员成功')
              this.$emit('update:open', false)
            })
          }
        }
      })
    },
    // 表单重置
    reset() {
      this.resetForm('form')
      this.form = {
        classIds: []
      }
    },
    cancel() {
      this.$emit('update:open', false)
      this.reset()
    }
  }
}
</script>
<style scoped lang="scss">
</style>
